package me.hl.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Created by Planck on 2016/2/25.
 */
public class NettyServerHandler extends ChannelHandlerAdapter {
    static private Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try{
            ByteBuf buf = (ByteBuf) msg;
            String recieved = getMessage(buf);
            logger.info("服务器收到消息[{}]",recieved);
            ctx.write(getSendByteBuf(recieved));
            ctx.flush();
            logger.info("已经发送消息");
        }catch (Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
        }finally {
            ReferenceCountUtil.release(msg);
        }
    }

    private String getMessage(ByteBuf buf){
        String message = "";
        try {
            byte[] con = new byte[buf.readableBytes()];
            buf.readBytes(con);
            message = new String(con);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }


    private ByteBuf getSendByteBuf(String str){
        byte[] req = str.getBytes();
        ByteBuf buf = Unpooled.buffer();
        buf.writeBytes(req);
        return buf;
    }
}
